﻿using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Web.Mvc;
using System.Web;
using System.Web.Script.Serialization;
using System.IO;
using System;
using WeBlog.Interfaces;
using WeBlog.Models;
using WeBlog.Services;
using WeBlog.Services.BlogML;


namespace WeBlog.Controllers {	
	[Authorize]        
	[Theme("Admin")]
	public class AdminController : ApplicationController
	{
		
		public AdminController( IUnitOfWork unitOfWork ) : base( unitOfWork )
		{            
		}

		public string ExtractSlug(string title) {
			return Utils.RemoveIllegalCharacters(title);            
		}

		[WeBlogAuthorize(Role.Admin), Theme("Admin")]
		public ActionResult Index()
		{
			var model = new SettingsViewModel();            
			return View(model);				
		}
		
		[HttpPost]
		[ValidateInput(false)]  //needed for tracking script  
		[WeBlogAuthorize(Role.Admin)]
		public ActionResult Index(FormCollection form)
		{
			var model = new SettingsViewModel();
			TryUpdateModel(model);

			if (!ModelState.IsValid)
				return View(model);
			
			SiteManager.Save(model.Settings);
			TempData.SetStatusMessage(Resources.Strings.Settings_SavedSuccessfully);
			return View(model);
			
		}

		[HttpPost]
		public string BlogMLImport(HttpPostedFileBase file)
		{
			var serializer = new JavaScriptSerializer();
			try
			{
			    if (file.ContentLength <= 0)
			        return serializer.Serialize(new {Message = "Nothing to import. File is empty.", Success = false});

			    var importer = new BlogMLImporter(UnitOfWork);
			    importer.ImportBlog(file.InputStream, CurrentUser.UserId);
			    return serializer.Serialize(new {Message = "Imported successfully!", Success = true});
			}
			catch (Exception ex)
			{
				return serializer.Serialize(new { Message = "Unable to parse the file. Error message: " + ex.Message, Success = false }); 
			}
		
		}
	}
}
